package com.mk.common.office;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.net.ConnectException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: yq
 * @Description:  直接用Openoffice将word、excel文档转化为html字符串的工具类
 * @Date: Created in 2:40 PM 3/19/18
 */
public class Doc2HtmlUtil {

    @Value("${openoffice.path}")
    private static String openOfficePath;

    /**
     * 将office文档转换为html文档
     * 测试.doc,.xls
     * 转化.pdf文件失败
     *
     * @param docFile   需要转换的文档
     * @param filepath  转换之后html的存放路径
     * @return  转换之后的html
     */
    public static File convert(File docFile,String filepath){
        //创建保存html的文件
        File htmlFile = new File(filepath + "/" + new Date().getTime() + ".html");
        Process pro = null;
        //创建OpenOffice连接
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
        try{
            if(openOfficePath.charAt(openOfficePath.length() - 1) != '\\'){
                openOfficePath += "\\";
            }
            //启动openoffice的服务
            String command = openOfficePath + "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\" -nofirststartwizard";
            pro = Runtime.getRuntime().exec(command);
            //连接
            connection.connect();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (ConnectException e){
            System.out.println("获取OpenOffice的连接失败...");
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        //创建转换器
        DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
        //转换文档向html
        converter.convert(docFile,htmlFile);
        //关闭openoffice的连接
        connection.disconnect();
        //关闭openoffice服务的进程
        pro.destroy();
        return htmlFile;
    }

    public static String office2HtmlString(File docFile,String filePath){
        //转换word文档
        File htmlFile = convert(docFile,filePath);
        //获取html文件流
        StringBuffer htmlSb = new StringBuffer();
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(htmlFile),"GBK"));
            while (br.ready()){
                htmlSb.append(br.readLine());
            }
            br.close();
            //删除html临时文件
//            htmlFile.delete();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        //html 文件字符串
        String htmlStr = htmlSb.toString();
        //把 html 中的table样式修改
        htmlStr.replaceAll("VOID","BOX");
        try{
            FileWriter fw = new FileWriter(htmlFile);
            fw.write(htmlStr);
            fw.flush();
            fw.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return htmlStr;
        //返回经过清洁的html文本
//        return clearFormat(htmlStr,filePath);
    }

    /**
     * 清除一些不需要的html标记
     *
     * @param htmlStr
     *            带有复杂html标记的html语句
     * @return 去除了不需要html标记的语句
     */
    protected static String clearFormat(String htmlStr, String docImgPath)
    {
        // 获取body内容的正则
        String bodyReg = "<BODY .*</BODY>";
        Pattern bodyPattern = Pattern.compile(bodyReg);
        Matcher bodyMatcher = bodyPattern.matcher(htmlStr);
        if (bodyMatcher.find())
        {
            // 获取BODY内容，并转化BODY标签为DIV
            htmlStr = bodyMatcher.group().replaceFirst("<BODY", "<DIV").replaceAll("</BODY>", "</DIV>");
        }
        // 调整图片地址
        htmlStr = htmlStr.replaceAll("<IMG SRC=\"", "<IMG SRC=\"" + docImgPath + "/");
        // 把<P></P>转换成</div></div>保留样式
        // content = content.replaceAll("(<P)([^>]*>.*?)(<\\/P>)",
        // "<div$2</div>");
        // 把<P></P>转换成</div></div>并删除样式
        htmlStr = htmlStr.replaceAll("(<P)([^>]*)(>.*?)(<\\/P>)", "<p$3</p>");
        // 删除不需要的标签
        htmlStr = htmlStr.replaceAll(
                "<[/]?(font|FONT|span|SPAN|xml|XML|del|DEL|ins|INS|meta|META|[ovwxpOVWXP]:\\w+)[^>]*?>", "");
        // 删除不需要的属性
        htmlStr = htmlStr.replaceAll(
                "<([^>]*)(?:lang|LANG|class|CLASS|style|STYLE|size|SIZE|face|FACE|[ovwxpOVWXP]:\\w+)=(?:'[^']*'|\"\"[^\"\"]*\"\"|[^>]+)([^>]*)>",
                "<$1$2>");
        return htmlStr;
    }
}
